package com.lhfeiyu.action.front.schedulers;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Table;
import com.lhfeiyu.po.AuctionGoods;
import com.lhfeiyu.po.AutoOffer;
import com.lhfeiyu.po.base.BaseSchedulers;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.service.AuctionGoodsService;
import com.lhfeiyu.service.AutoOfferService;
import com.lhfeiyu.service.base.BaseAA_UtilService;
import com.lhfeiyu.service.base.BaseSchedulersService;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.Result;
import com.lhfeiyu.util.base.RequestUtil;

@Controller
public class SchedulersAction {
	@Autowired
	private BaseSchedulersService schedulersService;
	@Autowired
	private AutoOfferService autoOfferService;
	@Autowired
	private AuctionGoodsService agService;
	@Autowired
	private BaseAA_UtilService utilService;

	private static Logger logger = Logger.getLogger("R");
	
	@ResponseBody
	@RequestMapping(value="/addOrUpdateTask", method=RequestMethod.POST)
	public JSONObject addOrUpdateTask(@ModelAttribute BaseSchedulers scheduler,HttpServletRequest request){
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = user.getId();
			String username = user.getUsername();
			//TODO 获取userId，存入receiver_id,用于通知用户,可考虑存入notcie表中，而不是scheduler表
			
			scheduler.setReceiverId(userId);//接收人
			
			Date date = new Date();
			Integer typeId = scheduler.getTaskTypeId();
			Integer noticeId = scheduler.getNoticeId();
			Integer linkId = scheduler.getLinkId();
			
//			scheduler.setUserId(userId);
			if(null == typeId || null == linkId || null == noticeId){
				return Result.failure(json, "信息不足，无法执行操作", "param_lack");
			}
			if(null == scheduler.getId()){//添加
				scheduler.setCreatedAt(date);
				scheduler.setCreatedBy(username);
				schedulersService.insert(scheduler);
			}else{//修改
				scheduler.setUpdatedAt(date);
				scheduler.setUpdatedBy(username);
				schedulersService.updateByPrimaryKeySelective(scheduler);
			}
			json.put("taskId", scheduler.getId());
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/addOrUpdateTask", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/delTask", method=RequestMethod.POST)
	public JSONObject delTask(HttpServletRequest request,@RequestParam(value="id") Integer id) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				json.put("toLogin",1);
			}
			//Integer userId = 0;
			String username = "";
			Map<String,Object> map = new HashMap<String,Object>();
			BaseSchedulers s = schedulersService.selectByPrimaryKey(id);
			if(null == s){
				json.put("status","failure");
				json.put("msg","开拍提醒已经被取消了");
			/*}else if(s.getUserId() != userId){
				json.put("status","failure");
				json.put("msg","您没有权限执行该操作");*/
			}else{
				map.put("table", Table.schedulers);
				map.put("id", id);
				map.put("username", username);
				utilService.deleteById(map);
				json.put("status","success");
				json.put("msg","已成功取消开拍提醒");
			}
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_删除开拍提醒出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getTask", method=RequestMethod.POST)
	public JSONObject getTask(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			Map<String, Object> map = RequestUtil.getRequestParam(request);//自动获取所有参数（查询条件）
			//sc_order格式例子：id___asc,created_at___desc,如果传递了request,则可自动获取分页参数
			BaseSchedulers schedulers = schedulersService.selectByCondition(map);
			if(null != schedulers){
				json.put("taskFlag", 1);
				json.put("task", schedulers);
			}
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载任务开拍提醒异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getTaskAndAutoOffer", method=RequestMethod.POST)
	public JSONObject getTaskAndAutoOffer(HttpServletRequest request) {
		List<BaseSchedulers> schedulersList = null;
		List<AutoOffer> autoOfferList = null;
		JSONObject json = new JSONObject();
		try {
			Map<String, Object> map = RequestUtil.getRequestParam(request);//自动获取所有参数（查询条件）
			//sc_order格式例子：id___asc,created_at___desc,如果传递了request,则可自动获取分页参数
			schedulersList = schedulersService.selectListByCondition(map);
			autoOfferList = autoOfferService.selectListByCondition(map);
			if(null != schedulersList && schedulersList.size()>0){
				json.put("taskFlag", 1);
				json.put("task", schedulersList.get(0));
			}
			if(null != autoOfferList && autoOfferList.size()>0){
				json.put("autoOfferFlag", 1);
				json.put("autoOffer", autoOfferList.get(0));
			}
			json.put("status", "success");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载任务开拍提醒和委托出价异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/addOrUpdateAutoOffer", method=RequestMethod.POST)
	public JSONObject addOrUpdateAutoOffer(@ModelAttribute AutoOffer autoOffer,HttpServletRequest request){
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			int userId = user.getId();
			autoOffer.setUserId(userId);//设置当前登陆人的ID
			String username = "";
			Date date = new Date();
			boolean returnFlag = false;
			Integer auctionType = autoOffer.getAuctionType();
			Integer auctionId = autoOffer.getAuctionId();
			Integer goodsId = autoOffer.getGoodsId();
			if(null == auctionType || null == auctionId || null == goodsId){
				json.put("msg", "信息不足，无法执行操作");returnFlag = true;
			}
			BigDecimal price = autoOffer.getTopPrice();
			Double priceInt = 0.0;
			if(null != price){
				priceInt = price.doubleValue();
				if(priceInt <= 10.0 || priceInt >100000.0){
					json.put("msg", "您输入的金额不正确");returnFlag = true;
				}
			}else{
				json.put("msg", "请输入金额");returnFlag = true;
			}
			if(true == returnFlag){
				json.put("status", "failure");return Result.success(json);
			}
			if(null == autoOffer.getId()){//添加
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("auctionType", auctionType);
				map.put("auctionId", auctionId);
				map.put("goodsId", goodsId);
				Integer count = autoOfferService.selectCountByCondition(map);
				if(null != count && count > 0){
					json.put("msg", "您已经设置开拍提醒，请勿重复设置");
					json.put("status", "failure");return Result.success(json);
				}
				autoOffer.setCreatedAt(date);
				autoOffer.setCreatedBy(username);
				int offerId = autoOfferService.insert(autoOffer);
				map.clear();
				map.put("auctionType", auctionType);
				map.put("auctionId", auctionId);
				map.put("goodsId", goodsId);
				List<AuctionGoods> agList = agService.selectListByCondition(map);
				if(null != agList && agList.size()>0){
					AuctionGoods ag = agList.get(0);
					BigDecimal topPriceBD = ag.getAutoTopPrice();
					boolean addFlag = true;
					if(null != topPriceBD){
						Double topPrice = topPriceBD.doubleValue();
						if(priceInt <= topPrice){
							addFlag = false;
						}
					}
					if(addFlag == true){
						AuctionGoods newAG = new AuctionGoods();
						newAG.setId(ag.getId());
						newAG.setAutoTopPrice(new BigDecimal(priceInt));
						newAG.setAutoUserId(userId);
						newAG.setAutoUsername(user.getUsername());
						newAG.setAutoOfferId(offerId);
						agService.updateByPrimaryKey(newAG);
					}
				}
			}else{//修改
				autoOffer.setUpdatedAt(date);
				autoOffer.setUpdatedBy(username);
				autoOfferService.updateByPrimaryKeySelective(autoOffer);
			}
			json.put("status", "success");
			json.put("id",autoOffer.getId());
			json.put("msg", "操作成功");
		}catch (Exception e) {
			e.printStackTrace();
			json.put("msg", "操作失败");
			Result.catchError(e, logger, "LH_ERROR_添加或修改委托出价出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/delAutoOffer", method=RequestMethod.POST)
	public JSONObject delAutoOffer(HttpServletRequest request,@RequestParam(value="id") Integer id) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			int userId = user.getId();
			String username = "";
			Map<String,Object> map = new HashMap<String,Object>();
			AutoOffer ao = autoOfferService.selectByPrimaryKey(id);
			if(null == ao){
				json.put("status","failure");
				json.put("msg","委托出价已经被取消了");
			}else if(ao.getUserId() != userId){
				json.put("status","failure");
				json.put("msg","您没有权限执行该操作");
			}else{
				map.put("table", Table.auto_offer);
				map.put("id", id);
				map.put("username", username);
				utilService.deleteById(map);
				json.put("status","success");
				json.put("msg","已成功取消委托出价");
				
				map.clear();
				map.put("autoOfferId", id);
				List<AuctionGoods> agList = agService.selectListByCondition(map);
				if(null != agList && agList.size()>0){//如果是最高委托价，就清空
					AuctionGoods ag = agList.get(0);
					map.clear();
					map.put("id", ag.getId());
					agService.updateAutoOfferNULL(map);
				}
			}
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_删除委托出价出现异常_", json);
		}
		return Result.success(json);
	}
	
}
